package com.xfcy.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xfcy.blog.common.R;
import com.xfcy.blog.common.constant.Constant;
import com.xfcy.blog.common.constant.RedisConstant;
import com.xfcy.blog.common.constant.SqlConstant;
import com.xfcy.blog.dto.PageDTO;
import com.xfcy.blog.mapper.PageMapper;
import com.xfcy.blog.entity.Page;
import com.xfcy.blog.service.PageService;
import com.xfcy.blog.utils.BeanCopyUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (Page)表服务实现类
 *
 * @author 晓风残月Lx
 * @since 2023-04-09 11:03:06
 */
@Service("pageService")
public class PageServiceImpl extends ServiceImpl<PageMapper, Page> implements PageService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 页面列表
     * @return
     */
    @Override
    public R listPage() {
        List<Page> pages = baseMapper.selectList(null);
        return R.success(pages);
    }

    /**
     * 新增页面
     * @param pageDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insertPage(PageDTO pageDTO) {
        Page page = BeanCopyUtil.copyObject(pageDTO, Page.class);
        int rows = baseMapper.insert(page);

        if (rows > 0) {
            // 存图片
            redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, pageDTO.getPageCover());
            return R.success();
        }

        return rows > 0 ? R.success(page): R.error("添加失败");
    }

    /**
     * 修改页面
     * @param pageDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updatePage(PageDTO pageDTO) {
        Page page = BeanCopyUtil.copyObject(pageDTO, Page.class);
        // 查询看图片是否改变
        Page plainPage = baseMapper.selectById(page.getId());

        int rows = baseMapper.updateById(page);

        if (!plainPage.getPageCover().equals(page.getPageCover()) && rows > Constant.ZERO) {
            // 可以用Lua脚本
            redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, plainPage.getPageCover());
            redisTemplate.opsForSet().add(RedisConstant.DB_FILE_UPLOAD_IMAGES, page.getPageCover());
            return R.success();
        }

        return rows > 0 ? R.success() : R.error("修改失败");
    }

    /**
     * 删除页面信息
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deletePage(Long id) {
        Page page = baseMapper.selectById(id);
        int rows = baseMapper.deleteById(id);

        if (rows > 0) {
            // 删除redis中存储的图片
            redisTemplate.opsForSet().remove(RedisConstant.DB_FILE_UPLOAD_IMAGES, page.getPageCover());
            return R.success();
        }
        return R.error("删除失败");
    }
}


